// pages/publish-order/publish-order.js
// import { SaveData } from "@/api/home";
import { Home } from "../../models/home";
// import { UploadFileByForm } from "@/api/upload";
import { Product } from "../../models/product";
// import { GetDataList } from "@/api/product";
// import { GetTheData } from "@/api/demand";
import { Demand } from "../../models/demand";
import { config } from "../../config/config";
import { UserInfo } from "../../models/userinfo";
import Toast from "../../miniprogram_npm/@vant/weapp/toast/toast";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    fileList: [],
    radioValue: "2",
    productList: [],
    show: false,
    typeName: "",
    typeId: "",
    number: 1,
    tags: [
      {
        value: "需要现货",
        type: ""
      },
      {
        value: "需要定制",
        type: ""
      },
      {
        value: "常规尺寸",
        type: ""
      },
      {
        value: "时间很赶",
        type: ""
      },
      {
        value: "颜色参考图片",
        type: ""
      },
      {
        value: "能做的厂家请报价联系",
        type: ""
      }
    ],
    id: "",
    title: "需要现货、常规尺寸、能做的厂家请报价联系",
    ContactInfo: "",
    btnDisable: false,
    userInfo: null,
    config
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    let data = new UserInfo();
    this.data.userInfo = data.getUserInfo();
    this.setData({
      userInfo: data.getUserInfo()
    });
    this.data.id = options.id || "";
    await this.getDataList();
    if (this.data.id) {
      this.getTheData(this.data.id);
    }
  },

  async getTheData(id) {
    const data = await Demand.GetTheData({ Id: id });
    let data2 = data.Data;
    this.data.title = data2.Title;
    const tags = data2.Content.split(",");
    if (tags.length > 0) {
      tags.forEach(item => {
        this.changeTagByName(item);
      });
      this.setData({
        tags: this.data.tags
      });
    }
    const Imags = data2.Imags.split(",");
    if (Imags.length > 0) {
      Imags.forEach(item => {
        this.data.fileList.push({
          url: item
        });
      });
      this.setData({
        fileList: this.data.fileList
      });
    }
    // this.number = data2.Number;
    this.findTypeById(data2.Demandclassifyid);
    // this.radioValue = data2.PopedomId;

    this.setData({
      number: data2.Number,
      radioValue: data2.PopedomId,
      ContactInfo: data2.ContactInfo,
      title: data2.Title
    });
  },
  findTypeById(id) {
    const data = this.data.productList.find(item => {
      return item.Id == id;
    });
    // this.data.typeId = id;
    this.setData({
      typeId: id,
      typeName: data.Name
    });
    // this.typeName = data.Name;
  },
  changeTagByName(name) {
    this.data.tags.map(item => {
      if (item.value == name) {
        item.type = "primary";
      }
    });
  },
  onChangeNumber(e) {
    this.data.number = e.detail;
  },
  onChangeTitle(e) {
    this.data.title = e.detail;
  },
  async getDataList() {
    let postData = {
      PageIndex: 1,
      PageRows: 10000,
      SortField: "id",
      SortType: "asc"
    };
    let data = await Product.GetDataList(postData);
    data.Data.map(item => {
      item.name = item.Name;
    });

    this.setData({
      productList: data.Data
    });
    // this.productList = data.Data;
  },
  // async afterRead(file) {
  //   let formData = new FormData();
  //   formData.append("fileList", file.file);
  //   const data = await UploadFileByForm(formData);

  //   let len = this.fileList.length;
  //   this.fileList[len - 1].url = data.url;
  // },
  afterRead(e) {
    console.log("afterRead");
    console.log(e);
    let that = this;
    let file = e.detail.file;
    e.detail.file.forEach(file => {
      wx.uploadFile({
        url: `${config.apiBaseUrl}Base_Manage/Upload/UploadFileByForm`, // 仅为示例，非真实的接口地址
        filePath: file.url,
        name: "file",
        // formData: { user: 'test' },
        success(res) {
          // 上传完成需要更新 fileList
          console.log(res.data);
          let data = JSON.parse(res.data);
          console.log(data.url);
          const { fileList = [] } = that.data;
          fileList.push({ ...file, url: data.url });
          that.setData({ fileList });
        }
      });
    });
  },
  onSelect(e) {
    console.log(e.detail.name);
    // this.typeName = e.name;
    // this.typeId = e.Id;
    // this.show = false;
    this.setData({
      typeName: e.detail.name,
      typeId: e.detail.Id,
      show: false
    });
  },
  deleteImg(e) {
    console.log(e.detail.index);
    this.data.fileList.splice(e.detail.index, 1);
    let fileList = this.data.fileList;
    this.setData({
      fileList
    });
    // console.log(this.fileList);
  },
  tounderstand() {},
  valid() {
    // 在 numberA 或者 numberB 被设置时，执行这个函数
    let flag = false;
    if (!this.data.title) {
      Toast("标题不能为空");
      flag = true;
      return true;
    }
    if (this.data.fileList.length == 0) {
      Toast("图片不能为空");
      flag = true;
      return true;
    }
    if (this.data.typeId == "") {
      Toast("类型不能为空");
      flag = true;
      return true;
    }
    return flag;
  },
  onChangePhone(e) {
    this.data.ContactInfo = e.detail;
  },
  async submit() {
    if (this.valid()) {
      return;
    }
    let list = [];
    this.data.fileList.forEach(item => {
      list.push(item.url);
    });
    let Imags = list.join(",");
    let tags = [];
    this.data.tags.forEach(item => {
      if (item.type) {
        tags.push(item.value);
      }
    });
    let tagsStr = tags.length > 0 ? tags.join(",") : "";
    let postData = {
      Id: this.data.id,
      CreatorId: this.data.userInfo.Id,
      CreateTime: new Date(),
      Title: this.data.title,
      Content: tagsStr,
      User_id: this.data.userInfo.Id,
      Demandclassifyid: this.data.typeId,
      // "PopedomId": this.radioValue,
      PopedomId: "1290559541989085184",
      Updatetime: new Date(),
      Number: this.data.number,
      Status: 0,
      Imags: Imags,
      ContactInfo: this.data.ContactInfo
      // PopedomNam: "普通"
    };

    console.log(postData);

    const data = await Home.SaveData(postData);
    if (data.Success) {
      Toast("发布成功");
      wx.navigateBack();
    } else {
      Toast(data.Msg);
    }
  },
  clickTag(e) {
    let index = e.currentTarget.dataset.index;
    let type = e.currentTarget.dataset.type;
    console.log(index);
    console.log(type);
    let tags = JSON.parse(JSON.stringify(this.data.tags));
    tags[index].type = !type ? "primary" : "";
    console.log();
    this.setData({
      tags
    });
    console.log(this.data.tags);
    // tags
  },
  typeShow() {
    this.setData({
      show: true
    });
  },

  selectRadio1() {
    this.setData({
      radioValue: 2
    });
  },

  selectRadio2() {
    this.setData({
      radioValue: 1
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {}
});
